import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  Input,
  OnChanges,
  OnInit,
  SimpleChanges,
  TemplateRef
} from '@angular/core';

import { ApesUpdateHostClassService } from '../core/services/update-host-class.service';
import { toBoolean } from '../core/util/convert';

@Component({
  selector           : 'apes-divider',
  templateUrl        : './apes-divider.component.html',
  providers          : [ ApesUpdateHostClassService ],
  preserveWhitespaces: false,
  changeDetection    : ChangeDetectionStrategy.OnPush
})
export class ApesDividerComponent implements OnChanges, OnInit {
  // region fields

  prefixCls = 'apes-divider';
  isText = false;
  textStr = '';
  textTpl: TemplateRef<void>;

  @Input()
  set apesText(value: string | TemplateRef<void>) {
    if (value instanceof TemplateRef) {
      this.textStr = null;
      this.textTpl = value;
    } else {
      this.textStr = value;
    }
    this.isText = !!value;
  }

  @Input() apesType: 'horizontal' | 'vertical' = 'horizontal';

  @Input() apesOrientation: 'left' | 'right' | '' = '';

  private _dashed = false;

  @Input()
  set apesDashed(value: boolean) {
    this._dashed = toBoolean(value);
  }

  get apesDashed(): boolean {
    return this._dashed;
  }

  // endregion
  private setClass(): void {
    const orientationPrefix = (this.apesOrientation.length > 0) ? '-' + this.apesOrientation : this.apesOrientation;
    const classMap = {
      [ `${this.prefixCls}` ]                              : true,
      [ `${this.prefixCls}-${this.apesType}` ]               : true,
      [ `${this.prefixCls}-with-text${orientationPrefix}` ]: this.isText,
      [ `${this.prefixCls}-dashed` ]                       : this.apesDashed
    };
    this.updateHostClassService.updateHostClass(this.el.nativeElement, classMap);
    this.cd.detectChanges();
  }

  constructor(private el: ElementRef, private cd: ChangeDetectorRef, private updateHostClassService: ApesUpdateHostClassService) {
  }

  ngOnChanges(changes: SimpleChanges): void {
    this.setClass();
  }

  ngOnInit(): void {
    this.setClass();
  }
}
